package com.zk.erp.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zk.erp.entity.Functions;
import com.zk.erp.service.IFunctionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private IFunctionsService functionsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication()
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123"))
                .authorities("select");*/
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        registry
                .antMatchers("/login","/error","/js/**").permitAll();
                //给每个url的权限进行验证
        List<Functions> list = functionsService.list();
        list.forEach(functions -> {
            if (StringUtils.isNotBlank(functions.getUrl())){
                registry.antMatchers(functions.getUrl()).hasAuthority(functions.getName());
            }
        });
        registry
                .anyRequest().authenticated()//其他的都要验证
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/index")
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                .and()
                .csrf().disable();
        //解决iframe不能跳转的问题，set 'X-Frame-Options' to 'deny'
        http.headers()
                .frameOptions()
                .sameOrigin()
                .httpStrictTransportSecurity()
                .disable();
    }
}
